<?php

/**
 * group actions.
 *
 * @package    jiazhang
 * @subpackage group
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class groupActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }
  
  //发布评论
  public function executeCreate_comment(sfWebRequest $request)
  {
        if($request->isMethod('POST')){
            
          $return_msg = array('error'=>0,'msg'=>'');  
          $theme_id = (int)$request->getParameter('post_id','');
          $user_id = (int)$request->getParameter('user_id','');
          $content = $request->getParameter('content','');
          $images = json_decode(trim($request->getParameter('pictures',array())));
          $theme = Doctrine::getTable('TalkTheme')->findOneById($theme_id);  
          $reply_id = (int)$request->getParameter('reply_id','');
          
          if(!$theme){
              $return_msg['error'] = 1;
              $return_msg['msg'] = '话题不存在';
              return $this->renderText(json_encode($return_msg));
          }
          
          if(strlen($content) == 0){
                $return_msg['error'] = 1;
                $return_msg['msg'] = '内容不能为空，说两句呗';
                return $this->renderText(json_encode($return_msg));
          }
          
          $theme_comment= new ThemeComment();
          $theme_comment->setUserId($user_id)->setThemeId($theme_id)->setParentId($reply_id)->setContent($content)->save();
          $theme->getAttr()->addCommentNum();
          if(count($images) >= 1){
              
              foreach($images as $img_url){
                  $theme_img = new ThemeCommentImages();
                  $theme_img->setImageUrl($img_url)->setThemeCommentId($theme_comment->getId())->save();
              }
          }
            $return_msg['error'] = 0;
            $return_msg['msg'] = '评论发表成功！';
            return $this->renderText(json_encode($return_msg));
        }
  }
  
  //我的帖子
  public function executeMy_theme(sfWebRequest $request){
      $user_id = (int)$request->getParameter('person_id',0);
      $page = (int)$request->getParameter('page',1);
      $page_size = (int)$request->getParameter('page_size',5);
      $dql = Doctrine::getTable('TalkTheme')->createQuery()->where('user_id = ?',$user_id)->andWhere('display = 1')->orderBy('created_at desc');
      $this->pager = new sfDoctrinePager('TalkTheme',$page_size);
      $this->pager->setQuery($dql);
      $this->pager->setPage($page);
      $this->pager->init();
      $theme_data = array();
      
            foreach($this->pager->getResults() as $key=>$theme){
                $theme_data[$key]['theme']['id'] = $theme->getGroup()->getId();
                $theme_data[$key]['theme']['title'] = $theme->getGroup()->getName();
                $theme_data[$key]['post']['id'] = $theme->getId();
                $theme_data[$key]['post']['title'] = $theme->getTitle();
                $theme_data[$key]['post']['createTime'] = $theme->getCreatedAt();
                $theme_data[$key]['post']['readers'] = $theme->getAttr()->getReadNum();
                $theme_data[$key]['post']['comments'] = $theme->getAttr()->getCommentNum();
            }
            
      return $this->renderText(json_encode($theme_data));
  }
  
  //发布话题
  public function executeCreate_theme(sfWebRequest $request){
      if($request->isMethod('POST')){
          $return_msg = array('error'=>0,'msg'=>'');  
          $group_id = $request->getParameter('theme_id','');
          $user_id = $request->getParameter('person_id','');
          $title = $request->getParameter('title','');
          $content = $request->getParameter('content','');
          $images = json_decode(trim($request->getParameter('picturs',array())));
          
          $group = Doctrine::getTable('Jgroup')->findOneById($group_id);
          $theme = new TalkTheme();
          $theme->setTitle($title)->setContent($content)->setUserId($user_id)->setGroupId($group_id)->save();
          $theme->createAttr();
          $group->addThemeNum();
          
          if(count($images) >= 1){
              $theme->setHasCover(1)->setCover($images[1])->save();
              
              foreach($images as $img_url){
                  $theme_img = new ThemeImage();
                  $theme_img->setImageUrl($img_url)->setThemeId($theme->getId())->save();
              }
          }
          
         $return_msg['error'] = 0;
         $return_msg['msg'] = '帖子发布成功';
         return $this->renderText(json_encode($return_msg));
      }
  }
  
  
  //关注,取消关注小组
  public function executeAttention(sfWebRequest $request){
      if($request->isMethod('POST')){
          $user_id = (int)$request->getParameter('person_id',0);
          $group_id = (int)$request->getParameter('theme_id',0);
          $return_msg = array('error'=>0,'msg'=>'');
          
          $group_user = Doctrine::getTable('GroupUser')->groupUserById($group_id,$user_id);
          $group = Doctrine::getTable('Jgroup')->findOneById($group_id);
          if(!$group) return $this->renderText(json_encode($return_msg));
          
          if(count($group_user) > 0){ 
                $group_user->delete();
                $group->decreasePeopleNum();
                $return_msg['error'] = 0;
                $return_msg['msg'] = '您已经退出了该小组！';
                return $this->renderText(json_encode($return_msg));
          }else{
            $group_user = new GroupUser();
            $group_user->setUserId($user_id)->setGroupId($group_id)->save();
            $group->addPeopleNum();

            $return_msg['error'] = 0;
            $return_msg['msg'] = '您已经成功加入了该小组！';
            return $this->renderText(json_encode($return_msg));
          }
      }
  }


  //帖子列表，话题列表
  public function executeTheme_list(sfWebRequest $request)
  {
      $group_id = (int)$request->getParameter('group_id',0);
      $user_id = (int)$request->getParameter('person_id',0);
      $page = (int)$request->getParameter('page',1);
      $page_size = (int)$request->getParameter('page_size',5);
      $dql = Doctrine::getTable('TalkTheme')->createQuery()->where('group_id = ?',$group_id)->andWhere('display = 1')->orderBy('created_at desc');
      $this->pager = new sfDoctrinePager('TalkTheme',$page_size);
      $this->pager->setQuery($dql);
      $this->pager->setPage($page);
      $this->pager->init();
      $group = Doctrine::getTable('Jgroup')->findOneById($group_id);
      $theme_data = array();
      
      if($page == 1){
          $theme_data['isFocus'] = (int)(($group->hasUserById($user_id)) ? true : false );
          $theme_data['personNum'] = $group->getPeopleNum();
          $theme_data['count'] = $group->getThemeNum();
      }
      
      $theme_data['postList'] = array();
      foreach($this->pager->getResults() as $key=>$theme){
            $theme_data['postList'][$key]['id'] = $theme->getId();
            $theme_data['postList'][$key]['title'] = $theme->getTitle();
            $theme_data['postList'][$key]['createTime'] = $theme->getCreatedAt();
            $theme_data['postList'][$key]['readers'] = $theme->getAttr()->getReadNum();
            $theme_data['postList'][$key]['comments'] =  $theme->getAttr()->getCommentNum();
            $theme_data['postList'][$key]['pictures'] = array();
            
            foreach($theme->getImg() as $i_key => $img){
                $theme_data['postList'][$key]['pictures'][$i_key] = $img->getImageUrl();
            }
            
        $theme_data['postList'][$key]['person'] = array();
        $theme_data['postList'][$key]['person']['id'] = $theme->getUser()->getId();
        $theme_data['postList'][$key]['person']['name'] = $theme->getUser()->getNickname();
        $theme_data['postList'][$key]['person']['icon'] = $theme->getUser()->getCover();
        $theme_data['postList'][$key]['person']['city'] = $theme->getUser()->getCity();
        $theme_data['postList'][$key]['person']['children'] = array();

        foreach($theme->getUser()->getChilds() as $i => $child){
            $theme_data['postList'][$key]['person']['children'][$i]['age'] = $child->getChildOld();
            $theme_data['postList'][$key]['person']['children'][$i]['sex'] = $child->getSexToString();
        }
        
      }
      
      return $this->renderText(json_encode($theme_data));
  }
  
  //帖子详情
  public function executeShow_theme(sfWebRequest $request){
//      $group_id = (int)$request->getParameter('theme_id',0);
      $theme_id = (int)$request->getParameter('post_id',0);
      $msg = array('error'=>'','msg'=>'');
      $theme = Doctrine::getTable('TalkTheme')->createQuery()->where('id = ?',$theme_id)->andWhere('display = 1')->execute();
      
      if(count($theme) == 0){
              $msg['error'] = 0;
              $msg['msg'] = '数据错误';
              return $this->renderText(json_encode($msg));
      }
      
      $theme_obj = $theme->getFirst();
      $theme_obj->getAttr()->addReadNum();
      $theme_data = array();
      
      $theme_data['id'] = $theme_obj->getId();
      $theme_data['title'] = $theme_obj->getTitle();
      $theme_data['pictures'] = array();
      
      foreach($theme_obj->getImg() as $i_key => $img){
            $theme_data['pictures'][$i_key] = $img->getImageUrl();
      }
            

    $theme_data['detail'] = $theme_obj->getContent();
    $theme_data['createTime'] = $theme_obj->getCreatedAt();
    $theme_data['readers'] = $theme_obj->getAttr()->getReadNum();
    $theme_data['comments'] = $theme_obj->getAttr()->getCommentNum();
    $theme_data['person']['id'] = $theme_obj->getUser()->getId();
    $theme_data['person']['name'] = $theme_obj->getUser()->getNickname();
    $theme_data['person']['icon'] = $theme_obj->getUser()->getCover();
    $theme_data['person']['city'] = $theme_obj->getUser()->getCity();
    $theme_data['person']['family'] = User::$roles[$theme_obj->getUser()->getRole()];
    $theme_data['person']['children'] = array();
    
    foreach($theme_obj->getUser()->getChilds() as $i => $child){
        $theme_data['person']['children'][$i]['age'] = $child->getChildOld();
        $theme_data['person']['children'][$i]['sex'] = $child->getSexToString();
    }
        
    $theme_data['commentList'] = array();
    
    foreach($theme_obj->getComments() as $comment_key => $comment){
        $theme_data['commentList'][$comment_key]['id'] = $comment->getId();
        $theme_data['commentList'][$comment_key]['content'] = $comment->getContent();
        $theme_data['commentList'][$comment_key]['picturs'] = array();
        
        foreach($comment->getImages() as $img_key => $image){
            $theme_data['commentList'][$comment_key]['picturs'][$img_key] = $image->getImageUrl();
        }

        $theme_data['commentList'][$comment_key]['person'] = array();
        $theme_data['commentList'][$comment_key]['person']['id'] = $comment->getUser()->getId();
        $theme_data['commentList'][$comment_key]['person']['name'] = $comment->getUser()->getNickname();
        $theme_data['commentList'][$comment_key]['person']['icon'] = $comment->getUser()->getCover();
        $theme_data['commentList'][$comment_key]['person']['city'] = $comment->getUser()->getCity();
        $theme_data['commentList'][$comment_key]['person']['children'] = array();

        foreach($theme_obj->getUser()->getChilds() as $i => $child){
            $theme_data['commentList'][$comment_key]['person']['children'][$i]['age'] = $child->getChildOld();
            $theme_data['commentList'][$comment_key]['person']['children'][$i]['sex'] = $child->getSexToString();
        }
    }
    
    return $this->renderText(json_encode($theme_data));
  }
  
  //最新回应
  public function executeNew_comment(sfWebRequest $request){
      sfConfig::set('sf_web_debug',false);
      $user_id = (int)$request->getParameter('user_id',0);
      $request_time = $request->getParameter('request_time',date('Y-m-d H:i:s'));
      $comment_data = array();
      $request_time = date("Y-m-d H:i:s",strtotime($request_time));
      $my_posts = Doctrine::getTable('TalkTheme')->createQuery()->where('user_id = ?',$user_id)->andWhere('display = 1')->execute();
      
          //计算最新的回应
          //首先计算我发的主题在请求时间后有没有新评论，第二步计算我评论的内容有没有人评论我的
          $theme_ids = $my_posts->toKeyValueArray('id', 'id');
          //在我的帖子中的我自己发的评论不算新回应
          $comments = Doctrine::getTable('ThemeComment')
                  ->createQuery()
                  ->whereIn('theme_id',$theme_ids)
                  ->andWhere('display = 1')
                  ->andWhere('user_id <> ?',$user_id)
                  ->andWhere('created_at > ?',$request_time)
                  ->andWhere('parent_id = 0')
                  ->execute();
          
          foreach($comments as $key=>$comment){
              $comment_data[$key]['post_id']  = $comment->getTheme()->getId();
              $comment_data[$key]['id']  = $comment->getId();
              $comment_data[$key]['content'] = $comment->getContent();
              $comment_data[$key]['picture'] = $comment->getFirstImg();
              $comment_data[$key]['commentTime'] = $comment->getCreatedAt();
              $comment_data[$key]['person'] = array();
//              if(!$comment->getUser()){
//                  $user = new User();
//              }else{
//                 $user = $comment->getUser();
//              }
              $comment_data[$key]['person']['id'] = $comment->getUser()->getId();
              $comment_data[$key]['person']['name'] = $comment->getUser()->getNickname();
              $comment_data[$key]['person']['icon'] = $comment->getUser()->getCover();
          }
          
          //这里统计无论在哪个帖子中我发的评论别人回复了我的，都算新回应
          $my_comment_ids = Doctrine::getTable('ThemeComment')->createQuery()->where('user_id = ?',$user_id)->andWhere('display = 1')->execute()->toKeyValueArray('id', 'id');
          $reply_my_comment = Doctrine::getTable('ThemeComment')->createQuery()->whereIn('parent_id',$my_comment_ids)->andWhere('display = 1')->andWhere('created_at > ?',$request_time)->execute();
          
          foreach($reply_my_comment as $key=>$comment){
              $comment_data[$key]['post_id']  = $comment->getTheme()->getId();
              $comment_data[$key]['id']  = $comment->getId();
              $comment_data[$key]['content'] = $comment->getContent();
              $comment_data[$key]['picture'] = $comment->getFirstImg();
              $comment_data[$key]['commentTime'] = $comment->getCreatedAt();
              $comment_data[$key]['person'] = array();
              $comment_data[$key]['person']['id'] = $comment->getUser()->getId();
              $comment_data[$key]['person']['name'] = $comment->getUser()->getNickname();
              $comment_data[$key]['person']['icon'] = $comment->getUser()->getCover();
          }
          
    return $this->renderText(json_encode($comment_data));
  }
  
//未关注小组列表
  public function executeGroup_list(sfWebRequest $request){
      sfConfig::set('sf_web_debug',false);
      $page = (int)$request->getParameter('page',1);
      $page_size = (int)$request->getParameter('page_size',5);

      $dql = Doctrine::getTable('Jgroup')->createQuery()->where('display = 1')->orderBy('created_at desc');
      $this->pager = new sfDoctrinePager('Jgroup',$page_size);
      $this->pager->setQuery($dql);
      $this->pager->setPage($page);
      $this->pager->init();
        
      $group_data = array();
      
      if($page == 1){
        $group_data['page_count'] = count($this->pager->getResults());
        $group_data['count'] = $this->pager->count();
      }  
      
     $group_data['themeList'] = array();
     
      foreach($this->pager->getResults() as $key=>$group){
        
          $group_data['themeList'][$key]['id'] = $group->getId();
          $group_data['themeList'][$key]['title'] = $group->getName();
          $group_data['themeList'][$key]['picture'] = $group->getCover();
          $group_data['themeList'][$key]['detail'] = $group->getDescripts();
          $group_data['themeList'][$key]['members'] = $group->getPeopleNum();
      }
      
    return $this->renderText(json_encode($group_data));    
  }
  
  //已关注小组列表
  public function executeMy_group_list(sfWebRequest $request){
      sfConfig::set('sf_web_debug',false);
      $user_id = (int)$request->getParameter('user_id',0);
      $page = (int)$request->getParameter('page',1);
      $page_size = (int)$request->getParameter('page_size',5);
      $request_time = $request->getParameter('request_time',date('Y-m-d H:i:s'));
      $request_time = date("Y-m-d H:i:s",strtotime($request_time));
      $group_ids = Doctrine::getTable('GroupUser')->createQuery()->where('user_id = ?',$user_id)->execute()->toKeyValueArray('group_id', 'group_id');
      $dql = Doctrine::getTable('Jgroup')->createQuery()->whereIn('id',$group_ids)->andWhere('display = 1')->orderBy('created_at desc');
      $this->pager = new sfDoctrinePager('Jgroup',$page_size);
      $this->pager->setQuery($dql);
      $this->pager->setPage($page);
      $this->pager->init();
        
      $group_data = array();
      
      if($page == 1){
          $my_posts = Doctrine::getTable('TalkTheme')->createQuery()->where('user_id = ?',$user_id)->andWhere('display = 1')->execute();
          $group_data['myPosts'] = $my_posts->count();
          //计算最新的回应
          //首先计算我发的主题在请求时间后有没有新评论，第二步计算我评论的内容有没有人评论我的
          $theme_ids = $my_posts->toKeyValueArray('id', 'id');
          //在我的帖子中的我自己发的评论不算新回应
          $comment_new_num = Doctrine::getTable('ThemeComment')
                  ->createQuery()
                  ->whereIn('theme_id',$theme_ids)
                  ->andWhere('display = 1')
                  ->andWhere('user_id <> ?',$user_id)
                  ->andWhere('created_at > ?',$request_time)
                  ->andWhere('parent_id = 0')
                  ->count();
          //这里统计无论在哪个帖子中我发的评论别人回复了我的，都算新回应
          $my_comment_ids = Doctrine::getTable('ThemeComment')->createQuery()->where('user_id = ?',$user_id)->andWhere('display = 1')->execute()->toKeyValueArray('id', 'id');
          $reply_my_comment = Doctrine::getTable('ThemeComment')->createQuery()->whereIn('parent_id',$my_comment_ids)->andWhere('display = 1')->andWhere('created_at > ?',$request_time)->count();
          $group_data['myReplies'] = $comment_new_num + $reply_my_comment;
      }  
      
     $group_data['page_count'] = count($this->pager->getResults());
     $group_data['count'] = $this->pager->count();
     $group_data['themeList'] = array();
     
      foreach($this->pager->getResults() as $key=>$group){
        
          $group_data['themeList'][$key]['id'] = $group->getId();
          $group_data['themeList'][$key]['title'] = $group->getName();
          $group_data['themeList'][$key]['picture'] = $group->getCover();
          $group_data['themeList'][$key]['detail'] = $group->getDescripts();
          $group_data['themeList'][$key]['members'] = $group->getPeopleNum();
      }
      
    return $this->renderText(json_encode($group_data));    
  }
  
}
